<!DOCTYPE html>
<html lang="zh">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no">
    <title>视频查询系统</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet">
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.7.2/font/bootstrap-icons.css">
    <style>
        .video-container {
            margin-top: 20px;
        }
        .video-item {
            margin-bottom: 15px;
            height: 100%;
            padding: 15px;
            border: 1px solid #ddd;
            border-radius: 5px;
            cursor: pointer;
            transition: background-color 0.2s;
        }
        .video-item:hover {
            background-color: #f8f9fa;
        }
        .modal-dialog {
            max-width: 800px;
            width: 90%;
            margin: 1.75rem auto;
        }
        .modal-content {
            background-color: #000;
        }
        .modal-header {
            background-color: #fff;
            border-bottom: 1px solid #dee2e6;
        }
        .modal-body {
            padding: 0;
            background-color: #fff;
        }
        .video-player-container {
            position: relative;
            width: 100%;
            padding-top: 56.25%; /* 16:9 比例 */
            background-color: #000;
        }
        .video-player-container video {
            position: absolute;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
        }
        #modalVideoInfo {
            padding: 1rem;
            background-color: #fff;
        }
        .video-info {
            margin-bottom: 10px;
        }
        .table {
            margin-bottom: 0;
        }
        .table td {
            padding: 8px;
        }
        .video-grid {
            display: grid;
            grid-template-columns: repeat(4, 1fr);
            gap: 15px;
            margin-bottom: 20px;
        }
        .video-info-compact {
            font-size: 0.9rem;
        }
        .video-info-compact .table td {
            padding: 4px;
        }
        .play-button {
            margin-top: 10px;
            width: 100%;
        }
        .header-container {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 2rem;
            padding-bottom: 1rem;
            border-bottom: 1px solid #eee;
        }
        .user-section {
            display: flex;
            align-items: center;
            gap: 15px;
        }
        .user-info {
            display: flex;
            align-items: center;
            gap: 8px;
            padding: 6px 12px;
            background-color: #f8f9fa;
            border-radius: 4px;
        }
        .user-info .username {
            font-weight: 500;
            color: #495057;
        }
        .container {
            padding-top: 40px;
        }
        /* 修改密码弹窗样式 */
        .password-modal .modal-dialog {
            max-width: 500px;
        }
        .password-modal .modal-content {
            background-color: #fff;
            border: none;
            border-radius: 8px;
            box-shadow: 0 2px 10px rgba(0,0,0,0.1);
        }
        .password-modal .modal-header {
            background-color: #f8f9fa;
            border-bottom: 1px solid #eee;
            border-radius: 8px 8px 0 0;
            padding: 1rem 1.5rem;
        }
        .password-modal .modal-title {
            color: #2c3e50;
            font-weight: 500;
        }
        .password-modal .modal-body {
            padding: 1.5rem;
        }
        .password-modal .modal-footer {
            background-color: #f8f9fa;
            border-top: 1px solid #eee;
            border-radius: 0 0 8px 8px;
            padding: 1rem 1.5rem;
        }
        .password-modal .form-label {
            color: #495057;
            font-weight: 500;
        }
        .password-modal .form-control {
            border: 1px solid #ced4da;
            border-radius: 4px;
            padding: 0.5rem 0.75rem;
        }
        .password-modal .form-control:focus {
            border-color: #80bdff;
            box-shadow: 0 0 0 0.2rem rgba(0,123,255,0.25);
        }
        .password-modal .alert {
            margin-bottom: 0;
            margin-top: 1rem;
        }
        .password-modal .btn-primary {
            background-color: #0d6efd;
            border: none;
            padding: 0.5rem 1.5rem;
        }
        .password-modal .btn-secondary {
            background-color: #6c757d;
            border: none;
            padding: 0.5rem 1.5rem;
        }
        /* 响应式布局样式 */
        @media (max-width: 768px) {
            /* 标题和用户信息区域 */
            .header-container {
                flex-direction: column;
                gap: 1rem;
                text-align: center;
            }
            .header-container h1 {
                font-size: 1.5rem;
            }
            .user-section {
                flex-direction: column;
                width: 100%;
            }
            .user-section button {
                width: 100%;
            }
            
            /* 查询表单 */
            .search-form-container {
                padding: 1rem;
            }
            
            /* 视频网格 */
            .video-grid {
                grid-template-columns: 1fr;
                gap: 10px;
            }
            
            /* 分页控件 */
            #pagination {
                flex-direction: column;
                align-items: center;
                gap: 1rem;
            }
            .pagination-controls {
                display: flex;
                gap: 0.5rem;
            }
            
            /* 弹窗 */
            .modal-dialog {
                margin: 0.5rem;
                max-width: 100%;
            }
            
            /* 表格样式 */
            .table td {
                padding: 4px;
                font-size: 0.9rem;
            }
        }
        /* 通用响应式优化 */
        .btn {
            white-space: nowrap;
        }
        
        .form-control, .form-select {
            font-size: 0.9rem;
        }
        
        /* 优化查询表单布局 */
        .search-form-container {
            background-color: #fff;
            border-radius: 8px;
            box-shadow: 0 1px 3px rgba(0,0,0,0.1);
        }

        /* 移动端优化 */
        @media (max-width: 768px) {
            .container {
                padding-top: 20px;
                padding-left: 10px;
                padding-right: 10px;
            }

            /* 标题区域 */
            .header-container {
                margin-bottom: 1rem;
            }
            .header-container h1 {
                font-size: 1.5rem;
                margin-bottom: 1rem;
            }

            /* 用户信息区域 */
            .user-section {
                flex-direction: column;
                gap: 0.5rem;
            }
            .user-section button {
                width: 100%;
                margin-bottom: 0.5rem;
            }
            .user-info {
                width: 100%;
                justify-content: center;
            }

            /* 查询表单 */
            .search-form-container {
                margin: 0 -10px;
                border-radius: 0;
            }
            .card-body {
                padding: 1rem;
            }
            .form-label {
                margin-bottom: 0.3rem;
                font-size: 14px;
            }
            .form-control, .form-select {
                height: 40px;
                font-size: 14px;
                margin-bottom: 0.5rem;
            }
            /* 移动端查询按钮样式 */
            .d-md-none .btn-primary {
                height: 44px;
                font-size: 16px;
                margin-top: 0.5rem;
                display: flex;
                align-items: center;
                justify-content: center;
                gap: 8px;
            }
            .d-md-none .bi-search {
                font-size: 18px;
            }
            /* 表单组间距 */
            .search-form-container .col-12 {
                margin-bottom: 0.5rem;
            }
            .search-form-container .col-12:last-child {
                margin-bottom: 0;
            }

            /* 视频列表 */
            .video-grid {
                grid-template-columns: 1fr;
                gap: 10px;
                margin: 10px 0;
            }
            .video-item {
                margin-bottom: 10px;
                padding: 10px;
            }
            .video-info-compact {
                font-size: 13px;
            }
            .video-info-compact .table td {
                padding: 3px;
            }
            .play-button {
                height: 36px;
                font-size: 14px;
            }

            /* 分页控件 */
            #pagination {
                flex-direction: column;
                gap: 1rem;
                margin-top: 1rem;
                padding: 10px;
            }
            .pagination-controls {
                width: 100%;
                justify-content: space-between;
            }
            .pagination-controls button {
                min-width: 80px;
            }

            /* 弹窗优化 */
            .modal-dialog {
                margin: 10px;
            }
            .modal-header {
                padding: 10px 15px;
            }
            .modal-body {
                padding: 15px;
            }
            .modal-title {
                font-size: 16px;
            }
            .modal-footer {
                padding: 10px 15px;
            }

            /* 表格样式 */
            .table {
                margin-bottom: 0;
            }
            .table td {
                padding: 5px;
                font-size: 13px;
            }

            /* 按钮样式 */
            .btn {
                padding: 8px 15px;
                font-size: 14px;
            }
            .btn-sm {
                padding: 5px 10px;
                font-size: 12px;
            }
        }

        /* 修改密码弹窗移动端优化 */
        @media (max-width: 768px) {
            .password-modal .modal-dialog {
                margin: 10px;
                width: auto;
            }
            .password-modal .modal-content {
                border-radius: 10px;
            }
            .password-modal .modal-body {
                padding: 15px;
            }
            .password-modal .form-control {
                height: 40px;
                font-size: 14px;
            }
            .password-modal .btn {
                height: 40px;
                font-size: 14px;
            }
        }

        /* 触摸设备优化 */
        @media (hover: none) {
            .video-item:hover {
                background-color: transparent;
            }
            .video-item:active {
                background-color: #f8f9fa;
            }
        }
    </style>
</head>
<body>
    <div class="container mt-4">
        <div class="header-container">
            <h1>视频查询系统</h1>
            <div class="user-section">
                <div class="user-info">
                    <i class="bi bi-person-circle"></i>
                    <span class="username" id="currentUser">加载中...</span>
                </div>
                <button class="btn btn-outline-primary" onclick="showChangePasswordModal()">
                    <i class="bi bi-key"></i> 修改密码
                </button>
                <button class="btn btn-outline-danger" onclick="logout()">
                    <i class="bi bi-box-arrow-right"></i> 退出
                </button>
            </div>
        </div>
        
        <div class="row mt-4">
            <div class="col">
                <div class="card search-form-container">
                    <div class="card-body">
                        <h5 class="card-title">查询条件</h5>
                        <form id="searchForm" class="row g-3">
                            <!-- 摄像头类型选择 -->
                            <div class="col-md-3 col-12">
                                <label class="form-label">摄像头类型</label>
                                <select class="form-select" id="cameraType">
                                    <option value="">全部</option>
                                    <option value="旋转摄像头">旋转摄像头</option>
                                    <option value="固定摄像头">固定摄像头</option>
                                </select>
                            </div>
                            <!-- 时间选择 -->
                            <div class="col-md-3 col-12">
                                <label class="form-label">开始时间</label>
                                <input type="datetime-local" class="form-control" id="startDateTime" required>
                            </div>
                            <div class="col-md-3 col-12">
                                <label class="form-label">结束时间</label>
                                <input type="datetime-local" class="form-control" id="endDateTime" required>
                            </div>
                            <!-- 每页显示条数 -->
                            <div class="col-md-2 col-12">
                                <label class="form-label">每页显示</label>
                                <select class="form-select" id="pageSize">
                                    <option value="10">10条</option>
                                    <option value="20" selected>20条</option>
                                    <option value="50">50条</option>
                                    <option value="100">100条</option>
                                </select>
                            </div>
                            <!-- PC端查询按钮 -->
                            <div class="col-md-1 d-none d-md-flex align-items-end">
                                <button type="submit" class="btn btn-primary w-100">查询</button>
                            </div>
                            <!-- 移动端查询按钮 -->
                            <div class="col-12 d-md-none">
                                <button type="submit" class="btn btn-primary w-100">
                                    <i class="bi bi-search"></i> 查询视频
                                </button>
                            </div>
                        </form>
                    </div>
                </div>
            </div>
        </div>

        <div id="videoList" class="video-container">
            <!-- 视频列表将在这里动态显示 -->
        </div>

        <div id="pagination" class="d-flex justify-content-between align-items-center mt-3 mb-4">
            <div class="pagination-info text-center">
                共 <span id="totalCount">0</span> 条记录
            </div>
            <div class="pagination-controls">
                <button class="btn btn-outline-primary btn-sm px-3" id="prevPage" disabled>
                    <i class="bi bi-chevron-left"></i> 上一页
                </button>
                <span class="mx-2">第 <span id="currentPage">1</span> 页</span>
                <button class="btn btn-outline-primary btn-sm px-3" id="nextPage" disabled>
                    下一页 <i class="bi bi-chevron-right"></i>
                </button>
            </div>
        </div>
    </div>

    <!-- 视频播放弹窗 -->
    <div class="modal fade" id="videoModal" tabindex="-1">
        <div class="modal-dialog modal-dialog-centered">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title">视频播放</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                </div>
                <div class="modal-body">
                    <div id="modalVideoInfo"></div>
                    <div class="video-player-container">
                        <div id="modalVideoPlayer"></div>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <!-- 添加修改密码的模态框 -->
    <div class="modal fade password-modal" id="changePasswordModal" tabindex="-1">
        <div class="modal-dialog modal-dialog-centered">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title">
                        <i class="bi bi-key"></i>
                        修改密码
                    </h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                </div>
                <div class="modal-body">
                    <form id="changePasswordForm">
                        <div class="mb-4">
                            <label class="form-label">当前密码</label>
                            <input type="password" class="form-control" id="oldPassword" required 
                                   placeholder="请输入当前密码">
                        </div>
                        <div class="mb-4">
                            <label class="form-label">新密码</label>
                            <input type="password" class="form-control" id="newPassword" required
                                   placeholder="请输入新密码（至少6位）">
                        </div>
                        <div class="mb-4">
                            <label class="form-label">确认新密码</label>
                            <input type="password" class="form-control" id="confirmPassword" required
                                   placeholder="请再次输入新密码">
                        </div>
                        <div id="passwordError" class="alert alert-danger d-none"></div>
                    </form>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
                    <button type="button" class="btn btn-primary" onclick="changePassword()">
                        <i class="bi bi-check2"></i> 确认修改
                    </button>
                </div>
            </div>
        </div>
    </div>

    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js"></script>
    <script>
        let videoModal;
        let currentPage = 1;
        let totalPages = 1;
        let changePasswordModal;

        document.addEventListener('DOMContentLoaded', function() {
            videoModal = new bootstrap.Modal(document.getElementById('videoModal'));
            setDefaultDateRange();
            getCurrentUser();
            changePasswordModal = new bootstrap.Modal(document.getElementById('changePasswordModal'));
        });

        function showVideo(video) {
            const startTime = new Date(video.StartTime * 1000).toLocaleString();
            const endTime = new Date(video.EndTime * 1000).toLocaleString();
            
            // 从路径中提取摄像头类型
            const cameraType = video.TargetPath.includes('旋转摄像头') ? '旋转摄像头' : '固定摄像头';
            
            // 更新弹窗中的视频信息
            document.getElementById('modalVideoInfo').innerHTML = `
                <table class="table">
                    <tr>
                        <td width="100"><strong>摄像头:</strong></td>
                        <td>${cameraType}</td>
                    </tr>
                    <tr>
                        <td><strong>开始时间:</strong></td>
                        <td>${startTime}</td>
                    </tr>
                    <tr>
                        <td><strong>结束时间:</strong></td>
                        <td>${endTime}</td>
                    </tr>
                </table>
            `;
            
            // 更新弹窗中的视频播放器
            document.getElementById('modalVideoPlayer').innerHTML = `
                <video controls preload="metadata">
                    <source src="/${video.TargetPath}" type="video/mp4">
                    您的浏览器不支持视频播放
                </video>
            `;
            
            videoModal.show();
        }

        async function loadVideos(page = 1) {
            const startDateTime = document.getElementById('startDateTime').value;
            const endDateTime = document.getElementById('endDateTime').value;
            const pageSize = document.getElementById('pageSize').value;
            const cameraType = document.getElementById('cameraType').value;
            
            try {
                const response = await fetch(
                    `/api/videos?start=${startDateTime}&end=${endDateTime}&page=${page}&pageSize=${pageSize}&cameraType=${encodeURIComponent(cameraType)}`
                );
                if (!response.ok) {
                    const error = await response.text();
                    throw new Error(`查询失败 (Query failed): ${error}`);
                }
                const data = await response.json();
                
                const videoList = document.getElementById('videoList');
                videoList.innerHTML = '';
                
                if (data.records.length === 0) {
                    videoList.innerHTML = '<div class="alert alert-info">未找到符合条件的视频</div>';
                    return;
                }

                // 创建网格容器
                const gridContainer = document.createElement('div');
                gridContainer.className = 'video-grid';
                videoList.appendChild(gridContainer);

                // 更新分页信息
                currentPage = data.page.page;
                totalPages = Math.ceil(data.page.total / data.page.pageSize);
                document.getElementById('totalCount').textContent = data.page.total;
                document.getElementById('currentPage').textContent = currentPage;
                
                // 更新分页按钮状态
                document.getElementById('prevPage').disabled = currentPage <= 1;
                document.getElementById('nextPage').disabled = currentPage >= totalPages;

                // 渲染视频列表
                data.records.forEach(video => {
                    const startTime = new Date(video.StartTime * 1000).toLocaleString();
                    const endTime = new Date(video.EndTime * 1000).toLocaleString();
                    const cameraType = video.TargetPath.includes('旋转摄像头') ? '旋转摄像头' : '固定摄像头';
                    
                    const videoElement = document.createElement('div');
                    videoElement.className = 'video-item';
                    videoElement.onclick = () => showVideo(video);
                    videoElement.innerHTML = `
                        <div class="video-info-compact">
                            <table class="table table-sm">
                                <tr>
                                    <td><strong>摄像头:</strong></td>
                                    <td>${cameraType}</td>
                                </tr>
                                <tr>
                                    <td><strong>开始:</strong></td>
                                    <td>${startTime}</td>
                                </tr>
                                <tr>
                                    <td><strong>结束:</strong></td>
                                    <td>${endTime}</td>
                                </tr>
                            </table>
                            <button class="btn btn-primary btn-sm play-button">
                                <i class="bi bi-play-fill"></i> 播放视频
                            </button>
                        </div>
                    `;
                    gridContainer.appendChild(videoElement);
                });
            } catch (error) {
                console.error('查询失败:', error);
                document.getElementById('videoList').innerHTML = `
                    <div class="alert alert-danger">
                        <h5>查询失败 (Query Failed)</h5>
                        <p>${error.message}</p>
                        <small class="text-muted">如果问题持续存在，请联系管理员 (Please contact administrator if the problem persists)</small>
                    </div>
                `;
            }
        }

        // 绑定分页事件
        document.getElementById('prevPage').addEventListener('click', () => {
            if (currentPage > 1) {
                loadVideos(currentPage - 1);
            }
        });

        document.getElementById('nextPage').addEventListener('click', () => {
            if (currentPage < totalPages) {
                loadVideos(currentPage + 1);
            }
        });

        // 修改表单提交事件
        document.getElementById('searchForm').addEventListener('submit', async (e) => {
            e.preventDefault();
            currentPage = 1; // 重置页码
            await loadVideos(1);
        });

        // 监听弹窗关闭事件，停止视频播放
        document.getElementById('videoModal').addEventListener('hidden.bs.modal', function () {
            const videoPlayer = document.getElementById('modalVideoPlayer');
            const videoElement = videoPlayer.querySelector('video');
            if (videoElement) {
                videoElement.pause();
                videoElement.currentTime = 0;
            }
        });

        function setDefaultDateRange() {
            const now = new Date();
            const start = new Date(now);
            start.setHours(0, 0, 0, 0);
            const end = new Date(now);
            end.setHours(23, 59, 59, 999);

            document.getElementById('startDateTime').value = formatDateTime(start);
            document.getElementById('endDateTime').value = formatDateTime(end);
        }

        function formatDateTime(date) {
            return date.toISOString().slice(0, 16);
        }

        // 获取当前用户信息
        async function getCurrentUser() {
            try {
                const response = await fetch('/api/current-user');
                if (!response.ok) {
                    throw new Error('获取用户信息失败 (Failed to get user info)');
                }
                const data = await response.json();
                document.getElementById('currentUser').textContent = data.username;
            } catch (error) {
                console.error('获取用户信息失败:', error);
                document.getElementById('currentUser').textContent = '未知用户 (Unknown)';
            }
        }

        // 退出登录
        function logout() {
            window.location.href = '/logout';
        }

        function showChangePasswordModal() {
            // 清空表单
            document.getElementById('changePasswordForm').reset();
            document.getElementById('passwordError').classList.add('d-none');
            changePasswordModal.show();
        }

        async function changePassword() {
            const oldPassword = document.getElementById('oldPassword').value;
            const newPassword = document.getElementById('newPassword').value;
            const confirmPassword = document.getElementById('confirmPassword').value;
            const errorDiv = document.getElementById('passwordError');

            // 验证新密码
            if (newPassword !== confirmPassword) {
                errorDiv.innerHTML = `
                    <strong>错误 (Error):</strong> 
                    两次输入的新密码不一致 (The new passwords do not match)
                `;
                errorDiv.classList.remove('d-none');
                return;
            }

            if (newPassword.length < 6) {
                errorDiv.innerHTML = `
                    <strong>错误 (Error):</strong> 
                    新密码长度不能小于6位 (New password must be at least 6 characters)
                `;
                errorDiv.classList.remove('d-none');
                return;
            }

            try {
                const response = await fetch('/api/change-password', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                    },
                    body: JSON.stringify({
                        oldPassword,
                        newPassword,
                    }),
                });

                if (!response.ok) {
                    const error = await response.text();
                    throw new Error(error);
                }

                // 修改成功
                changePasswordModal.hide();
                alert('密码修改成功！(Password changed successfully!)');
            } catch (error) {
                errorDiv.innerHTML = `
                    <strong>错误 (Error):</strong> 
                    ${error.message.includes('旧密码不正确') ? 
                        '旧密码不正确 (Incorrect old password)' : 
                        `操作失败 (Operation failed): ${error.message}`}
                `;
                errorDiv.classList.remove('d-none');
            }
        }
    </script>
</body>
</html> 